import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * PDF操作工具类
 */
public class PDFUtil {

    @Test
    public  void  GenerateGuaranteeOnline(){
        // 模板文件路径
        String inputFileName = "D:\\cyp\\testPdf\\a1.pdf";
        // 生成的文件路径
        String outputFileName = "D:\\cyp\\testPdf\\bb.pdf";

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        PdfStamper stamper = null;

        try {
            os = new FileOutputStream(new File(outputFileName));
            // 2 读入pdf表单
            reader = new PdfReader(inputFileName);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            form.setFieldProperty("", "textsize", new Float(12), null);
            // 5给表单添加中文字体
            BaseFont bf = BaseFont.createFont("Font/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            form.addSubstitutionFont(bf);
            // 6查询数据================================================
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("guaranteeNo", "HLDB202303160001");
            data.put("tenderer", "开封市公安局");
            data.put("enterpriseName", "郑州信源信息技术股份有限公司");
            data.put("projectName", "【系统测试】工程公开保函测试项目20221205-001-C");
            data.put("sectionName", "第二标段");
            data.put("merchantName", "河南省浩隆担保有限责任公司");
            data.put("address", "开封市中山路中段86号");
            data.put("bond", "800000");
            data.put("year", "2023");
            data.put("month", "03");
            data.put("day", "16");
            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }
            ps.setFormFlattening(true);
            System.out.println("===============PDF导出成功=============");
        } catch (Exception e) {
            System.out.println("===============PDF导出失败=============");
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
